<script lang="ts" setup>
import Sidebar from "~/components/sidebar.vue";
import DockArea from "~/components/dock_area.vue";
import TabArea from "~/components/tab_area.vue";

import { TabUtil, tabPrices, tabSetting, labSetting } from '~/util/tab_util'
import themeManager from "~/util/theme_manager";
import { PairInfo, SwapInfo } from "~/models/Tracking";
import { ITab } from "~/models";

const tabList = ref([] as (ITab | null)[])
const tabIndex = ref(0)
const showDock = ref(true)

const openComponent = (item: any) => {
  const compIndex = TabUtil.find(tabList.value, item)
  if (compIndex >= 0) {
    tabIndex.value = compIndex
    return
  }
  tabList.value.push(item);
  tabIndex.value = tabList.value.length - 1;
}

const onChange = (i: number) => {
  // Monitor
  if (i == 0) {
    showDock.value = !showDock.value
  }
  // Price List
  else if (i == 1) {
    showDock.value = false
    openComponent(tabPrices)
  }
  // Setting
  else if (i == -1) {
    showDock.value = false
    openComponent(tabSetting)
  }
  // Lab
  else if (i == -2) {
    showDock.value = false
    openComponent(labSetting)
  }
}

const openWatcher = (payloads: {swap: SwapInfo, pair: PairInfo}) => {

  const tab = {
    ...payloads,
    type: 'monitor',
    title: payloads.pair.name
  } as ITab
  
  const watchIndex = TabUtil.find(tabList.value, tab)
  if (watchIndex >= 0) {
    tabIndex.value = watchIndex
    return
  }
  tabList.value.push(tab);
  tabIndex.value = tabList.value.length - 1;
}

const onClose = (index: number) => {
  tabList.value[index] = null
  if (index == tabIndex.value) {
    // find forward
    for (let i = index; i < tabList.value.length; i++) {
      if (tabList.value[i] != null) {
        tabIndex.value = i
        return
      }
    }
    // find backward
    for (let i = index - 1; i >= 0; i--) {
      if (tabList.value[i] != null) {
        tabIndex.value = i
        return
      }
    }
  }
}

onMounted(() => {
  // if (window.origin.match('localhost')) {
  //   setTimeout(() => {
  //     onChange(-2)
  //   }, 200)
  // }
})

</script>

<template>
  <div id="page-home" :style="themeManager.pageStyle()">
    <Sidebar @change="onChange" />
    <DockArea @open="openWatcher" v-show="showDock" />
    <TabArea :list="tabList" :activeIndex="tabIndex" @close="onClose" />
  </div>
</template>


<style scoped>
#page-home {
  overflow: hidden;
  min-height: 100vh;
  display: flex;
}
</style>
